import Vue from 'vue';
import Router from 'vue-router';
import Login from '../views/Login.vue';
import Main from '../views/Main.vue';

Vue.use(Router);

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        component: Login
    },
    {
        path: '/main',
        component: Main,
        meta: { requiresAuth: true }
    }
];

const router = new Router({
    mode: 'history',
    routes
});

router.beforeEach((to, from, next) => {
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
    const isAuthenticated = localStorage.getItem('username'); // 检查 localStorage 中是否有用户名

    if (requiresAuth && !isAuthenticated) {
        next('/login'); // 如果需要认证但未认证，跳转到登录页面
    } else {
        next(); // 否则正常跳转
    }
});

export default router;